﻿/*
 * Created by: Gregory Atchley-Martin
 * 
 * Project Start Date: 04/15/08
 * Project Completion Date: Ongoing
 * 
 * Purpose:
 *  This program was orginally designed as a only a html source code editor, now it has
 *  expanded to include a WYSIWYG editor, support for multiple programming languages, and 
 *  even project management.
 *  
 * Condition: 
 *  Still being built. Key functionallity added but it needs revising and to be fully tested.
 *  
 * Needs to get fixed:
 * 
 * 
 * 
 * Comments:
 * 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GAM_Web_Designer_Pro.Forms;
using ColorRichTextBox.ColorRichTextBox;
using GAM_Web_Designer_Pro.Properties;
using System.IO;

namespace GAM_Web_Designer_Pro {
    public partial class MainForm : Form {
        
        // This stores the active form.
        private DocumentForm _activeForm = null;

        // This is our list of schemes.
        public static SortedList<string, clsColorRichTextBoxSchema> CurrentSchemas = SchemaAccess.LoadAllSchemas();

        // The current project.
        private Project _currentProject = null;

        // A list of currently open forms.
        public List<DocumentForm> CurrentForms;

        public DocumentForm ActiveChildForm {
            get {
                return _activeForm;
            }
            set {
                _activeForm = value;
            }
        }

        public Project CurrentProject {
            get {
                return _currentProject;
            }
            set {
                _currentProject = value;
            }
        }
        
        public MainForm() {
            InitializeComponent();
            CurrentForms = new List<DocumentForm>();
        }

        #region " ( ToolStrip Events ) "

        private void newToolStripButton1_Click( object sender, EventArgs e ) {
            if ( _currentProject == null )
                projectToolStripMenuItem1_Click( sender, e );
            else
                toolStripButton3_Click( sender, e );
        }

        private void openToolStripButton1_Click( object sender, EventArgs e ) {
            openToolStripMenuItem1_Click( sender, e );
        }

        private void openProjectToolStrip_Click( object sender, EventArgs e ) {
            openProjectToolStripMenuItem_Click( sender, e );
        }

        private void saveToolStripButton1_Click( object sender, EventArgs e ) {
            saveToolStripMenuItem1_Click( sender, e );
        }

        private void toolStripButton2_Click( object sender, EventArgs e ) {
            saveAllToolStripMenuItem_Click( sender, e );
        }

        private void printToolStripButton1_Click( object sender, EventArgs e ) {
            printToolStripMenuItem1_Click( sender, e );
        }

        private void cutToolStripButton_Click( object sender, EventArgs e ) {
            cutToolStripMenuItem1_Click( sender, e );
        }

        private void copyToolStripButton_Click( object sender, EventArgs e ) {
            copyToolStripMenuItem1_Click( sender, e );
        }

        private void pasteToolStripButton_Click( object sender, EventArgs e ) {
            pasteToolStripMenuItem1_Click( sender, e );
        }

        private void helpToolStripButton1_Click( object sender, EventArgs e ) {
            // TODO: Code Method
        }

#endregion

        #region " ( Menu Item Events ) "
        private void projectToolStripMenuItem1_Click( object sender, EventArgs e ) {
            NewProjectForm form = new NewProjectForm();
            if ( form.ShowDialog( this ) == DialogResult.OK ) {
                _currentProject = form.CurrentProject;
            }
        }

        private void fileToolStripMenuItem2_Click( object sender, EventArgs e ) {
            new NewFileForm( this ).ShowDialog( this );
        }

        private void templateToolStripMenuItem1_Click( object sender, EventArgs e ) {
            new NewFileTemplateForm().ShowDialog( this );
        }

        private void openToolStripMenuItem1_Click( object sender, EventArgs e ) {
            try {
                // We need to make a list of extension filters used for
                // the openFileDialog.
                StringBuilder ofdFilter = new StringBuilder();
                StringBuilder filterExten;

                foreach ( clsColorRichTextBoxSchema item in CurrentSchemas.Values ) {
                    ofdFilter.Append( item.SchemeType + " Files " );
                    filterExten = new StringBuilder();
                    for ( int i = 0; i < item.ExtensionsSupported.Length; i++ ) {
                        if ( i == 0 ) {
                            filterExten.Append( "*" + item.ExtensionsSupported[ i ] );
                            continue;
                        }
                        filterExten.Append( ";*" + item.ExtensionsSupported[ i ] );
                    }
                    string temp = filterExten.ToString();
                    ofdFilter.Append( "(" + temp.Replace( '|', ',' ) + ")|" );
                    if ( CurrentSchemas.IndexOfValue( item ) == CurrentSchemas.Values.Count - 1 )
                        ofdFilter.Append( filterExten.ToString() );
                    else
                        ofdFilter.Append( filterExten.ToString() + "|" );
                }

                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.Personal );
                openFileDialog.Filter = ofdFilter.ToString();
                if ( openFileDialog.ShowDialog( this ) == DialogResult.OK ) {
                    string FileName = openFileDialog.FileName;
                    clsColorRichTextBoxSchema currentSchema = null;

                    for ( int i = 0; i < CurrentSchemas.Values.Count; i++ ) {
                        if ( currentSchema != null )
                            break;

                        for ( int x = 0; x < CurrentSchemas.Values[ i ].ExtensionsSupported.Length; x++ ) {
                            if ( FileName.EndsWith( CurrentSchemas.Values[ i ].ExtensionsSupported[ x ] ) ) {
                                currentSchema = new clsColorRichTextBoxSchema( CurrentSchemas.Values[ i ] );
                                break;
                            }
                        }
                    }

                    if ( currentSchema == null )
                        currentSchema = new clsColorRichTextBoxSchema( clsColorRichTextBoxSchema.enDefaultColorSchemaTypes.Other );

                    DocumentForm form;
                    if ( currentSchema.SchemeType.Equals( "HTML" ) )
                        form = new DocumentForm( FileName, currentSchema, this, true );
                    else
                        form = new DocumentForm( FileName, currentSchema, this, false );

                    form.MdiParent = this;
                    form.Text = FileName;
                    CurrentForms.Add( form );
                    _activeForm = form;
                    form.Show();
                }
            }
            catch ( Exception ex ) {
                new BugReporter.BugReporterForm( Application.ProductName,
                  Application.ProductVersion, ex.ToString(), ex.Message ).Show();
            }
        }

        private void openProjectToolStripMenuItem_Click( object sender, EventArgs e ) {
            try {
                string ext = Settings.Default.ProjectExt;
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.Personal ) + Settings.Default.UsersProjectDir;
                openFileDialog.Filter = "Web Designer Projects (*" + ext + ")|*" + ext;
                if ( openFileDialog.ShowDialog( this ) == DialogResult.OK ) {
                    PostStatusUpdate( "Loading Project...", 30 );
                    string file = openFileDialog.FileName;
                    _currentProject = ProjectAccess.LoadProject( file );
                    PostStatusUpdate( 85 );
                    projectPanelUserControl1.ReDrawDirectory( _currentProject.Directory, _currentProject.Name );
                    projectPanelUserControl1.Visible = true;
                }
                PostStatusUpdate( 100 );
                ResetStatusUpdate();
            }
            catch ( Exception ex ) {
                new BugReporter.BugReporterForm( Application.ProductName,
                  Application.ProductVersion, ex.ToString(), ex.Message ).Show();
            }
        }

        private void saveToolStripMenuItem1_Click( object sender, EventArgs e ) {
            try {
                _activeForm.SaveFile();
                PostStatusUpdate( _activeForm.Text + " Saved" );
                ResetStatusUpdate();
            }
            catch ( NullReferenceException ) {
            }
        }

        private void saveAsToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( saveFileDialog1.ShowDialog() == DialogResult.OK ) {
                string file = saveFileDialog1.FileName;
                _activeForm.SaveFile( file );
            }
        }

        private void closeToolStripMenuItem_Click( object sender, EventArgs e ) {
            _activeForm.Close();
            _activeForm = null;
        }

        private void closeProjectToolStripMenuItem_Click( object sender, EventArgs e ) {
            foreach ( DocumentForm doc in CurrentForms ) {
                doc.Close();
            }
            _activeForm = null;
            _currentProject = null;
            projectPanelUserControl1.Visible = false;
        }

        private void printToolStripMenuItem1_Click( object sender, EventArgs e ) {
            // TODO: add printer code.
        }

        private void printPreviewToolStripMenuItem1_Click( object sender, EventArgs e ) {
            // TODO: add print preview code.
        }

        private void exitToolStripMenuItem1_Click( object sender, EventArgs e ) {
            this.Close();
        }

        private void undoToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "Undo", false, null );
                else
                    _activeForm._sourceRTB.Undo();
            }
        }

        private void redoToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "Redo", false, null );
                else
                    _activeForm._sourceRTB.Redo();
            }
        }

        private void cutToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "Cut", false, null );
                else
                    _activeForm._sourceRTB.Cut();
            }
        }

        private void copyToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "Copy", false, null );
                else
                    _activeForm._sourceRTB.Copy();
            }
        }

        private void pasteToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "Paste", false, null );
                else
                    _activeForm._sourceRTB.Paste();
            }
        }

        private void selectAllToolStripMenuItem1_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "SelectAll", false, null );
                else
                    _activeForm._sourceRTB.SelectAll();
            }
        }

        private void deselectAllToolStripMenuItem_Click( object sender, EventArgs e ) {
            if ( _activeForm != null ) {
                if ( _activeForm.WasDesigning )
                    _activeForm._designWB.Document.ExecCommand( "Unselect", false, null );
                else
                    _activeForm._sourceRTB.DeselectAll();
            }
        }

        private void customizeToolStripMenuItem_Click( object sender, EventArgs e ) {
            // TODO: Code Method
        }

        private void optionsToolStripMenuItem1_Click( object sender, EventArgs e ) {
            // TODO: Code Method
        }

        private void toolStripMenuItem2_Click( object sender, EventArgs e ) {
            LayoutMdi( MdiLayout.Cascade );
        }

        private void tileVerticalToolStripMenuItem1_Click( object sender, EventArgs e ) {
            LayoutMdi( MdiLayout.TileVertical );
        }

        private void tileHorizontalToolStripMenuItem1_Click( object sender, EventArgs e ) {
            LayoutMdi( MdiLayout.TileHorizontal );
        }

        private void arrangeIconsToolStripMenuItem1_Click( object sender, EventArgs e ) {
            LayoutMdi( MdiLayout.ArrangeIcons );
        }

        private void toolbarToolStripMenuItem1_Click( object sender, EventArgs e ) {
            toolStrip.Visible = toolbarToolStripMenuItem1.Checked;
        }

        private void statusbarToolStripMenuItem1_Click( object sender, EventArgs e ) {
            statusStrip.Visible = statusbarToolStripMenuItem1.Checked;
        }
    
        private void saveAllToolStripMenuItem_Click( object sender, EventArgs e ) {
            foreach ( DocumentForm form in CurrentForms ) {
                form.SaveFile();
            }
        }

        private void closeAllToolStripMenuItem1_Click( object sender, EventArgs e ) {
            foreach ( DocumentForm form in CurrentForms ) {
                form.Close();
            }
            _activeForm = null;
        }
        #endregion

        private void toolStripButton3_Click( object sender, EventArgs e ) {
            // ColorRichTextBox.ColorRichTextBox.clsColorRichTextBoxSchema schema = new ColorRichTextBox.ColorRichTextBox.clsColorRichTextBoxSchema( ColorRichTextBox.ColorRichTextBox.clsColorRichTextBoxSchema.enDefaultColorSchemaTypes.Other );
            // new ColorRichTextBox.frmSchema( schema ).Show();
            new NewProjectTemplateForm().ShowDialog( this );
        }

        private void pictureBox1_Click( object sender, EventArgs e ) {
            if ( _currentProject != null ) {
                if ( projectPanelUserControl1.Visible == true ) {
                    this.pictureBox1.Image = global::GAM_Web_Designer_Pro.Properties.Resources.projectShow;
                    projectPanelUserControl1.Visible = false;
                }
                else {
                    this.pictureBox1.Image = global::GAM_Web_Designer_Pro.Properties.Resources.projectHide;
                    projectPanelUserControl1.Visible = true;
                }
            }
        }

        private void MainForm_Load( object sender, EventArgs e ) {
            projectPanelUserControl1.CurrentParent = this;
            printToolStripMenuItem1.Visible = false;
            printPreviewToolStripMenuItem1.Visible = false;
            toolStripSeparator18.Visible = false;
            printPreviewToolStripButton.Visible = false;
        }

        private void projectPanelUserControl1_Load( object sender, EventArgs e ) {

        }

        private void fileToolStripMenuItem1_Click( object sender, EventArgs e ) {

        }

        private void MainForm_FormClosing( object sender, FormClosingEventArgs e ) {

            // First we need to get a list of temporay files in the directory.
            string path = Application.StartupPath + Settings.Default.TemporayFileDir;
            DirectoryInfo info = new DirectoryInfo( path );
            FileInfo[] files = info.GetFiles();

            // After we get the list we just go through it one file at a time and delete it.
            for ( int i = 0; i < files.Length; i++ ) {
                files[i].Delete();                
            }

        }

        /// <summary>
        /// Post a status update to the form.
        /// </summary>
        /// <param name="msg">The message to post.</param>
        protected void PostStatusUpdate( string msg ) {
            statusToolStripStatusLabel.Text = msg;
        }

        /// <summary>
        /// Posts a status update.
        /// </summary>
        /// <param name="msg">The message to post.</param>
        /// <param name="progress">The amount of progress for the progress bar.</param>
        protected void PostStatusUpdate( string msg, int progress ) {
            statusToolStripStatusLabel.Text = msg;
            progressToolStripProgressBar.Value = progress;
        }

        /// <summary>
        /// Posts a status update.
        /// </summary>
        /// <param name="progress">The amount of progress for the progress bar.</param>
        protected void PostStatusUpdate( int progress ) {
            progressToolStripProgressBar.Value = progress;
        }

        /// <summary>
        /// Resets the status update timer.
        /// </summary>
        protected void ResetStatusUpdate() {
            statusTimer.Start();
        }

        /// <summary>
        /// Resets the status update timer and sets an intial interval.
        /// </summary>
        /// <param name="interval">The interval for the timer.</param>
        protected void ResetStatusUpdate( int interval ) {
            statusTimer.Interval = interval;
            statusTimer.Start();
        }

        // Is called every time the statusTimer ticks.
        private void statusTimer_Tick( object sender, EventArgs e ) {
            statusToolStripStatusLabel.Text = "Status";
            progressToolStripProgressBar.Value = 0;
            statusTimer.Stop();
            statusTimer.Interval = 1000;
        }
    }
}
